package com.bo.day20240912;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 二叉树的按层遍历
 * 依据队列实现
 * 先把头节点放入队列中，然后从队列中取出，访问，再把左右节点放入队列中，循环往复，直到队列为空
 *
 * 图解：https://cloud.fynote.com/share/d/1HKLV8IX
 * @Author: gpb
 * @Date: 2024/9/12 11:12
 * @Description:
 */
public class BinaryTreeTraversal {
    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node (int v) {
            value = v;
        }
    }

    public static void binaryTreeLevelTraversal (Node head) {
        if (head == null) {
            return;
        }
        Queue<Node> queue = new LinkedList<>();
        queue.offer(head);
        while (!queue.isEmpty()) {
            Node node = queue.poll();
            System.out.println(node.value);
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
        }
    }

    public static void main (String[] args) {
        Node head = new Node(1);
        head.left = new Node(2);
        head.right = new Node(3);
        head.left.left = new Node(4);
        head.left.right = new Node(5);
        head.right.left = new Node(6);
        head.right.right = new Node(7);
        head.right.right.left = new Node(8);
        head.right.right.right = new Node(9);
        binaryTreeLevelTraversal(head);
    }
}
